<template>
  <d2-container>
  <section class="vue-wrap">
    <div class="search" style="padding-top:10px;padding-bottom:10px;">
      <el-row class="vue-header" :span="24">
        <el-col :xs="5">
        </el-col>
        <el-col :xs="19" class="top-but-box" style="text-align: right">
          <!--<el-button type="info" size="small">查询</el-button>-->
          <el-button type="info" icon="plus" size="small" @click="addItem(true,'','editForm')">新建</el-button>
          <el-button v-if="isAuth('ecs:ecsquotainfo:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="vue-body" style="margin-top:10px;">
      <el-table :data="dataList" fit border :height="containerHeight" >
        <!--<el-table-column prop="ordinalNumber" label="序号" width="80"></el-table-column>-->
        <el-table-column prop="quotaName" label="指标名称" minWidth="160" align="center"></el-table-column>
        <el-table-column prop="normal" label="额定值/增幅值" minWidth="150" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.quotaType==0">额定值</span>
            <span v-if="scope.row.quotaType==1">增幅值</span>
          </template>
        </el-table-column>
        <el-table-column prop="upVal" label="上限" minWidth="100" align="center"></el-table-column>
        <el-table-column prop="downVal" label="下限" minWidth="100" align="center"></el-table-column>
        <el-table-column prop="addedVal" label="增幅值" minWidth="100" align="center"></el-table-column>
        <el-table-column prop="routine_type" label="指标周期" minWidth="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.quotaUnit==1">{{scope.row.quotaCycle}}(分钟)</span>
            <span v-if="scope.row.quotaUnit==2">{{scope.row.quotaCycle}}(小时)</span>
            <span v-if="scope.row.quotaUnit==3">{{scope.row.quotaCycle}}(天)</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" show-overflow-tooltip min-width="180" align="center">
          <template slot-scope="scope">
            <el-button type="success" icon="eye" size="small" @click="viewItem(false,scope.row)">查看</el-button>
            <el-button type="success" icon="edit" size="small" @click="addItem(false,scope.row,'editForm')">修改</el-button>
            <el-button type="danger" icon="delete" size="small" @click="delItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="page.page_no"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.page_size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper">
         </el-pagination>
      </template>
    </div>
    <el-dialog :title="editForm.title" :visible.sync="editForm.show" >
      <el-form :model="editForm.data" :rules="editForm.rules" label-position="right" ref="editForm" label-width="110px" class="demo-ruleForm">
            <el-form-item label="指标名称" prop="unit_name">
              <el-input v-model="editForm.data.name"></el-input>
            </el-form-item>
            <el-form-item label="监控指标" prop="unit_type">
              <el-radio v-model="editForm.data.unit_type" label="1">额定值</el-radio>
              <el-radio v-model="editForm.data.unit_type" label="2">增幅值</el-radio>
            </el-form-item>
            <el-form-item label="类型" prop="unit_device" v-if="editForm.data.unit_type==2">
              <el-radio v-model="editForm.data.unit_device" label="1">设备</el-radio>
              <el-radio v-model="editForm.data.unit_device" label="2">区域</el-radio>
              <el-radio v-model="editForm.data.unit_device" label="3">部门</el-radio>
            </el-form-item>
            <el-form-item label="计量对象" prop="meter_code" v-if="editForm.data.unit_device==1">
              <template>
                <el-select v-model="editForm.data.meter_code" multiple :disabled="meterCode" @change="setMeterCode" :value-key="editForm.data.meter_code" style="width:100%;">
                  <el-option v-for="item in meterCodeOption"
                             :key="item.code"
                             :label="item.name"
                             :value="item.code">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <el-form-item label="计量对象" prop="meter_code" v-if="editForm.data.unit_device==3||editForm.data.unit_device==2">
              <template>
                <el-input :placeholder="tree.inputPlace"
                  style="width:100%"
                  class="filter-item"
                  :suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"
                  @click.native="deptogglePanel($event)"
                  v-model="editForm.data.departName">
                </el-input>
                <div v-if="showTree" class="objectTree" style="width:100%" ref="suoShuMenTree">
                  <el-tree
                    :style="'height:'+containerHeight+'px'"
                    ref="departTree"
                    highlight-current
                    :show-checkbox="true"
                    node-key="id"
                    :data="treeDataList"
                    :expand-on-click-node="false"
                    :props="menuListTreeProps"
                    @check-change="selectDepart"
                    default-expand-all
                  ></el-tree>
                </div>
              </template>
            </el-form-item>
            <!-- <el-form-item label="监控指标" prop="meter_para">
              <el-select v-model="editForm.data.meter_para" :disabled="meterPara">
                <el-option v-for="item in meterParaOption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code">
                </el-option>
              </el-select>
            </el-form-item> -->

            <!-- <el-form-item label="额定值" prop="normal" v-if="editForm.data.unit_type==1">
              <el-input v-model="editForm.data.normal"></el-input>
            </el-form-item> -->
            <el-form-item label="增幅值" prop="normal" v-if="editForm.data.unit_type==2">
              <el-input v-model="editForm.data.normal"></el-input>
            </el-form-item>
            <el-form-item label="上限" prop="max" v-if="editForm.data.unit_type==1">
              <el-input v-model="editForm.data.max"></el-input>
            </el-form-item>
            <el-form-item label="下限" prop="min" v-if="editForm.data.unit_type==1">
              <el-input v-model="editForm.data.min"></el-input>
            </el-form-item>
            <el-form-item label="监控周期" prop="routine_type">
              <el-input v-model="editForm.data.routine_type" class="input-with-select">
                  <el-select v-model="editForm.data.routine_type_unit" slot="append" placeholder="请选择">
                    <el-option label="分钟" value="1"></el-option>
                    <el-option label="小时" value="2"></el-option>
                    <el-option label="天"   value="3"></el-option>
                  </el-select>
              </el-input>
            </el-form-item>
            <el-form-item label="备注" prop="memo">
            <el-input v-model="editForm.data.memo"></el-input>
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="button" @click="editForm.show = false">取消</el-button>
        <el-button type="primary" @click="submitForm('editForm')">确定</el-button>
      </div>
    </el-dialog>
  </section>
  </d2-container>
</template>

<script>
  import * as Util from "@/utils";
  import Config from "@/utils/config"
  import commondef from '@/utils/common'

  export default {
    components: {
    },
    data () {
      return {
        dataForm:{
          key:'',
        },
        menuListTreeProps: {
          label: "buildingName",
          children: "children"
        },
        tree:{
          inputPlace:'',
          inputName:'',
        },
        treeDataList:[],
        currentData:[],
        showTree:false,

        meterCode: false,
        meterPara: true,
        meterCodeOption: [],
        meterParaOption: [],
        count: '',
        customer_id: this.$store.state.customer_id,
        coltor_id: '',
        query: '',
        dataList: [],
        page: {
          page_size: commondef.globlePagesize,
          total: null,
          page_no: 1
        },
        editForm: {
          title: '新增指标设置',
          bAddState: false,
          show: false,
          currentSelectRow: {},
          data: {
            name:'',
            meter_code: '',
            meter_code_new: '',
            meter_para: '',
            meter_para_new: '',
            normal: '',
            max: '',
            min: '',
            routine_type: '',
            memo: '',
            unit_type:'1',
            unit_device:'1',
            departName:'',
            routine_type_unit:'1',//监控周期单位
          }
        },
        buildingList:[],
        orgList:[],
      }
    },
    computed:{
      containerHeight() {
        return Util.getClientHeight() - 233;
      },
    },
    created(){
      this.getBuildInfoList();
      this.getDepartList();
      this.getDataList();
    },
    methods: {
      // 获取区域树
      getBuildInfoList() {
        this.$http({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
          method: "get",
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000,
            'key': '',
            customerId: this.$cookie.get("customer_id"),
            projectid:this.$cookie.get("cuuren_projectId")
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.buildingList = Util.treeDataTranslate(data.menuList,"buildingId","parentBuildingId");
          } else {
            this.buildingList = [];
          }
        });
      },
      // 获取部门数据列表
      getDepartList () {
        this.$http({
          url: this.$http.adornUrl('/ecs/ecsorganizationinfo/select'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10000,
            'key': '',
            "customerId":this.$cookie.get('customer_id')
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.orgList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
          } else {
            this.orgList = []
          }
        })
      },

      deptogglePanel (event) {
          event || (event = window.event)
          event.stopPropagation
            ? event.stopPropagation()
            : (event.cancelBubble = true)
          this.showTree ? this.dephide() : this.depshow()
      },
      depshow () {
        this.showTree = true
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephide () {
        this.showTree = false
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephidePanel (e) {
        if (
          this.$refs.suoShuMenTree &&
          !this.$refs.suoShuMenTree.contains(e.target)
        ) {
          this.dephide()
        }
      },
      selectDepart(){
        let build = this.$refs.departTree.getCheckedNodes();
      //  console.log(build);
        this.currentData = [];
        this.editForm.data.departName=''
        if(this.editForm.data.unit_device==2){
          if(build.length>0){
            build.forEach((ele,index)=>{
              this.currentData.push(ele.buildingId);
              this.editForm.data.departName+=ele.buildingName;
              if(index<build.length-1){
                 this.editForm.data.departName+=",";
              }
            })
          }
        }
        else if(this.editForm.data.unit_device==3){
           if(build.length>0){
            build.forEach((ele,index)=>{
              this.currentData.push(ele.organizationId);
              this.editForm.data.departName+=ele.organizationName;
              if(index<build.length-1){
                 this.editForm.data.departName+=",";
              }
            })
          }
        }
        this.showTree = false;
      },
      setMeterCode (val) {
        var that = this
      //  console.log('this.meterCode...', this.meterCode, 'this.editForm.data.meter_code...', this.editForm.data.meter_code)
        if (this.meterCode === false && this.editForm.data.meter_code !== '') {
          setTimeout(() => {
            that.meterPara = false
          }, 100)
     //     console.log('this.meterPara', that.meterPara)
        } else {
          this.meterPara = true
        }

        this.getMeterPara(val)
      },
      getMeterCode () {
        var para = {
          page_no: 1,
          page_size: this.page.page_size,
          customer_id: this.customer_id,
          coltor_id: parseInt(this.coltor_id)
        }
    //    console.log('meter_code...', para)
        api.axiosRequest(api.urlList.colt.meters.get_list, para).then(res => {
          if (res.code === commondef.resCode.OK) {
            this.meterCodeOption = []
            for (var i = 0; i < res.rows.length; i++) {
              this.meterCodeOption.push({name: res.rows[i].meter_name, code: res.rows[i].code + ',' + res.rows[i].enegcate_code})
            }
     //       console.log('this.meterCodeOption...', this.meterCodeOption)
          }
        })
      },
      getMeterPara (val) {
        var para = {
          page_no: 1,
          page_size: this.page.page_size,
          enegcate_code: val.split(',')[1]
        }
    //    console.log('this.meterCodeOption.enegcate_code', val.split(',')[1])
        api.axiosRequest(api.urlList.mgr.dict.coltparas.get_list, para).then(res => {
          if (res.code === commondef.resCode.OK) {
       //     console.log(res)
            this.meterParaOption = []
            for (var j = 0; j < res.list.length; j++) {
              this.meterParaOption.push({name: res.list[j].name, id: res.list[j].id, code: res.list[j].code})
            }
       //     console.log(this.meterParaOption, res.list[0].enegcate_code)
          }
        })
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/ecs/ecsquotainfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.page.page_no,
            'limit': this.page.page_size,
            'key': this.dataForm.key,
            customerId: this.$cookie.get("customer_id"),
            projectid:this.$cookie.get("cuuren_projectId")
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.page.total = data.page.totalCount
          } else {
            this.dataList = []
            this.page.total = 0
          }
          this.dataListLoading = false
        })
      },
       // 每页数
      sizeChangeHandle (val) {
        this.page.page_size = val
        this.page.page_no = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.page.page_no = val
        this.getDataList()
      },
      viewItem(row){

      },
      addItem (type, row, form) {
        this.editForm.show = true
        this.editForm.bAddState = type
        if (this.$refs[form]) {
          this.$refs[form].resetFields()
        }
        if (type) {
          this.customer_id
          this.editForm.title = '新增指标设置'
          this.editForm.data.meter_code = ''
          this.editForm.data.meter_para = ''
          this.editForm.data.normal = ''
          this.editForm.data.max = ''
          this.editForm.data.min = ''
          this.editForm.data.routine_type = ''
          this.editForm.data.memo = ''
          this.meterPara = true
          this.meterCode = false
        } else {
    //      console.log('row', row)
          this.customer_id
          this.editForm.title = '编辑指标设置'
          this.editForm.data.meter_code = row.meter_name
          this.editForm.data.meter_code_new = row.meter_code
          this.editForm.data.meter_para = row.meter_para_name
          this.editForm.data.meter_para_new = row.meter_para
          this.editForm.data.normal = row.normal
          this.editForm.data.max = row.max
          this.editForm.data.min = row.min
          this.editForm.data.routine_type = row.routine_type
          this.editForm.data.memo = row.memo
          this.meterPara = true
          this.meterCode = true
        }
      },
      delItem (row) {
        this.$confirm('此操作将永久删除此项目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('delItem...', row)
          var para = {
            customer_id: this.customer_id,
            meter_code: row.meter_code,
            meter_para: row.meter_para
          }
          api.axiosRequest(api.urlList.enterprise.monitoridx.remove, para)
            .then(res => {
              if (res.code === commondef.resCode.OK) {
                this.getEnegcateList()
                this.$message.success(commondef.editWord.deleteSuccess)
              } else {
                this.$message.error(commondef.editWord.deleteError)
              }
            })
        })
      },
      submitForm (form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            var para = {
              customer_id: this.customer_id,
              meter_code: this.editForm.data.meter_code.split(',')[0],
              meter_para: this.editForm.data.meter_para,
              normal: this.editForm.data.normal,
              max: this.editForm.data.max,
              min: this.editForm.data.min,
              routine_type: parseInt(this.editForm.data.routine_type),
              notes:this.editForm.data.notes
            }
            console.log('addpara...', para)
            if (!this.editForm.bAddState) {
              para = {
                customer_id: this.customer_id,
                meter_code: this.editForm.data.meter_code_new,
                meter_para: this.editForm.data.meter_para_new,
                normal: this.editForm.data.normal,
                max: this.editForm.data.max,
                min: this.editForm.data.min,
                routine_type: parseInt(this.editForm.data.routine_type),
                memo: this.editForm.data.memo
              }
              console.log('para', para)
              api.axiosRequest(api.urlList.enterprise.monitoridx.modify, para)
                .then(res => {
                  if (res.code === commondef.resCode.OK) {
                    this.editForm.show = false
                    this.getEnegcateList()
                    this.$message.success(commondef.editWord.modifySuccess)
                  } else {
                    this.$message.error(commondef.editWord.modifyError)
                  }
                })
            } else {
              this.$http({
                url: this.$http.adornUrl(`/ecs/ecsbuildingascription/${!this.dataForm.id ? 'save' : 'update'}`),
                method: 'post',
                data: this.$http.adornData({
                  'id': this.dataForm.id || undefined,
                  'buildingId': this.dataForm.buildingId,
                  'ascriptionType': this.dataForm.ascriptionType,
                  'subscriberId': this.dataForm.subscriberId,
                  'organizationId': this.dataForm.organizationId,
                  "customerId":this.$cookie.get('customer_id')
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                  this.visible = false
                this.$emit('refreshDataList')
              }
              })
              } else {
                this.$message.error(data.msg)
              }
            })
            }
          } else {
            console.log('validate failed')
            return false
          }
        })
      }
    },
    mounted () {
      if (this.$store.state.customer_id === undefined) {
        //this.$store.dispatch('DomainName').then(res => {
          this.customer_id = this.$store.state.customer_id
          // this.getMeterCode()
          // this.getEnegcateList()
        //})
      } else {
        // this.getMeterCode()
        // this.getEnegcateList()
      }
    },
    watch:{
      'editForm.data.unit_device'(newValue,oldValue){
        this.showTree = false;
        this.editForm.data.departName = '';
        if(this.editForm.data.unit_device==2){
          this.tree.inputPlace ='请选择区域信息';
          this.tree.inputName="选择区域";
          this.menuListTreeProps ={
            label: "buildingName",
            children: "children"
          };
          this.treeDataList = this.buildingList;
        }else if(this.editForm.data.unit_device==3){
          this.tree.inputPlace ='请选择部门信息';
          this.tree.inputName="选择部门";
          this.menuListTreeProps={
            label: "organizationName",
            children: "children"
          };
          this.treeDataList = this.orgList;
        }
      }
    }
  }
</script>
<style>
 .input-with-select .el-input-group__append {
    background-color: #fff;
    width: 80px;
  }
</style>
<style scoped lang="scss">
  @import "../../assets/scss/_variables";
  .objectTree {
      position: absolute;
      overflow: auto;
      z-index: 100;
      height: 200px;
      /* border: 1px solid #ddd; */
      line-height: normal;
      z-index: 204;
      box-shadow: 0px 0px 1px 1px #e2dfdf;
      margin-top: 3px;
      border-radius: 4px;
    background-color: white;
  }
</style>
